package com.ruoyi.merchant.shopverification.service.impl;

import java.util.List;

import com.ruoyi.merchant.shop.domain.Shop;
import com.ruoyi.merchant.shop.mapper.ShopMapper;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.ruoyi.merchant.shopverification.mapper.ShopVerificationMapper;
import com.ruoyi.merchant.shopverification.domain.ShopVerification;
import com.ruoyi.merchant.shopverification.service.IShopVerificationService;
import com.ruoyi.merchant.shopverification.service.IEnterpriseVerificationService;
import com.ruoyi.common.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 店铺认证信息Service业务层处理
 *
 * @author zzr
 * @date 2025-09-14
 */
@Service
public class ShopVerificationServiceImpl implements IShopVerificationService {

    private static final Logger logger = LoggerFactory.getLogger(ShopVerificationServiceImpl.class);

    @Autowired
    private ShopVerificationMapper shopVerificationMapper;

    @Autowired
    private IEnterpriseVerificationService enterpriseVerificationService;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 查询店铺认证信息
     *
     * @param id 店铺认证信息主键
     * @return 店铺认证信息
     */
    @Override
    public ShopVerification selectShopVerificationById(Integer id) {
        return shopVerificationMapper.selectShopVerificationById(id);
    }

    /**
     * 查询店铺认证信息列表
     *
     * @param shopVerification 店铺认证信息
     * @return 店铺认证信息
     */
    @Override
    public List<ShopVerification> selectShopVerificationList(ShopVerification shopVerification) {
        return shopVerificationMapper.selectShopVerificationList(shopVerification);
    }

    /**
     * 新增店铺认证信息
     *
     * @param shopVerification 店铺认证信息
     * @return 结果
     */
    @Override
    public int insertShopVerification(ShopVerification shopVerification) {
        logger.info("开始处理店铺认证信息，前端发送的信息: {}", shopVerification);

        // 参数校验
        if (shopVerification == null) {
            logger.error("店铺认证信息不能为空");
            throw new ServiceException("店铺认证信息不能为空");
        }

        // 获取企业认证所需的关键信息
        String legalPerson = shopVerification.getDirector(); // 负责人作为法定代表人
        String creditNo = shopVerification.getBusinessLicenseId(); // 营业执照号码作为统一社会信用代码
        Shop shop1 = shopMapper.selectShopById(shopVerification.getMid());
        String companyName = shop1.getName();

        // 参数完整性校验
        if (legalPerson == null || legalPerson.trim().isEmpty()) {
            logger.error("负责人信息不能为空");
            throw new ServiceException("负责人信息不能为空");
        }

        if (creditNo == null || creditNo.trim().isEmpty()) {
            logger.error("营业执照号码不能为空");
            throw new ServiceException("营业执照号码不能为空");
        }

        if (companyName == null || companyName.trim().isEmpty()) {
            logger.error("店铺名称不能为空");
            throw new ServiceException("店铺名称不能为空");
        }

        logger.info("开始进行企业认证，法定代表人: {}, 统一社会信用代码: {}, 企业名称：{}", legalPerson, creditNo, companyName);

        try {
            // 调用企业认证服务进行验证
            boolean isVerified = enterpriseVerificationService.verifyEnterpriseInfo(creditNo, legalPerson, companyName);

            // 获取店铺信息
            Shop shop = null;
            if (shopVerification.getMid() != null) {
                shop = shopMapper.selectShopById(shopVerification.getMid());
            }

            if (!isVerified) {
                logger.error("企业认证失败，法定代表人: {}, 统一社会信用代码: {}, 企业名称：{}", legalPerson, creditNo,companyName);

                // 如果店铺存在，修改审核状态为2（人工审核）
                if (shop != null) {
                    shop.setAuditStatus(2);
                    shopMapper.updateShop(shop);
                    logger.info("企业认证失败，已将店铺审核状态设置为人工审核，店铺ID: {}", shop.getId());
                } else {
                    logger.warn("企业认证失败，但未找到对应的店铺信息，店铺ID: {}", shopVerification.getMid());
                }

                throw new ServiceException("企业认证失败，请检查负责人姓名和营业执照号码是否正确");
            }

            logger.info("企业认证成功，开始保存店铺认证信息");

            // 认证成功，如果店铺存在，修改审核状态为1（审核通过）
            if (shop != null) {
                shop.setAuditStatus(1);
                shopMapper.updateShop(shop);
                logger.info("企业认证成功，已将店铺审核状态设置为审核通过，店铺ID: {}", shop.getId());

                String mobile = shopVerification.getMobile();
                
                // 用户注册功能
                // 如果企业认证成功，就在系统用户表里注册商家信息
                if (mobile != null && !mobile.trim().isEmpty()) {
                    try {
                        Long userId = registerMerchantUser(mobile, shop);
                        logger.info("商家用户注册成功，手机号: {}, 用户ID: {}", mobile, userId);
                        
                        // 为该用户授予角色权限，角色id为100
                        assignUserRole(userId, 100L);
                        
                    } catch (Exception e) {
                        logger.error("商家用户注册失败，手机号: {}", mobile, e);
                        // 用户注册失败不影响主流程，只记录日志
                    }
                } else {
                    logger.warn("手机号为空，跳过用户注册");
                }

            } else {
                logger.warn("企业认证成功，但未找到对应的店铺信息，店铺ID: {}", shopVerification.getMid());
            }

            // 企业认证通过后，保存店铺认证信息
            int result = shopVerificationMapper.insertShopVerification(shopVerification);


            if (result > 0) {
                logger.info("店铺认证信息保存成功，ID: {}", shopVerification.getId());
                return result;
            } else {
                logger.error("店铺认证信息保存失败");
                throw new ServiceException("店铺认证信息保存失败");
            }

        } catch (ServiceException e) {
            // 重新抛出业务异常
            throw e;
        } catch (Exception e) {
            logger.error("企业认证过程中发生异常", e);
            throw new ServiceException("企业认证过程中发生异常: " + e.getMessage());
        }
    }

    /**
     * 修改店铺认证信息
     *
     * @param shopVerification 店铺认证信息
     * @return 结果
     */
    @Override
    public int updateShopVerification(ShopVerification shopVerification) {
        return shopVerificationMapper.updateShopVerification(shopVerification);
    }

    /**
     * 批量删除店铺认证信息
     *
     * @param ids 需要删除的店铺认证信息主键
     * @return 结果
     */
    @Override
    public int deleteShopVerificationByIds(Integer[] ids) {
        return shopVerificationMapper.deleteShopVerificationByIds(ids);
    }

    /**
     * 删除店铺认证信息信息
     *
     * @param id 店铺认证信息主键
     * @return 结果
     */
    @Override
    public int deleteShopVerificationById(Integer id) {
        return shopVerificationMapper.deleteShopVerificationById(id);
    }

    /**
     *
     *@return 关联查询的所有店铺信息结果
     */
    @Override
    public List<ShopVerification> selectAllShopVerification(Integer mid) {
        return shopVerificationMapper.selectAllShopVerification(mid);
    }

    /**
     * @param mobile 手机号
     * @return 关联店铺的id
     */
    @Override
    public ShopVerification selectShopVerificationByMobile(String mobile) {
        return shopVerificationMapper.selectShopVerificationByMobile(mobile);
    }

    /**
     * 注册商家用户
     *
     * @param mobile 手机号
     * @param shop 店铺信息
     * @return 用户ID
     */
    private Long registerMerchantUser(String mobile, Shop shop) {
        logger.info("开始注册商家用户，手机号: {}, 店铺名称: {}", mobile, shop.getName());
        
        // 创建系统用户对象
        SysUser sysUser = new SysUser();
        
        // 设置基本信息
        sysUser.setUserName(mobile);           // 用户名使用手机号
        sysUser.setNickName(mobile);           // 昵称使用手机号
        sysUser.setPhonenumber(mobile);        // 手机号
        sysUser.setStatus("0");                // 状态：0-正常，1-停用，默认正常
        sysUser.setDelFlag("0");               // 删除标志：0-存在，2-删除，默认存在
        sysUser.setPassword("123456");         // 设置默认密码都为123456
        
        // 设置备注信息
        sysUser.setRemark("商家用户，店铺ID: " + shop.getId() + ", 店铺名称: " + shop.getName());
        
        // 设置创建时间
        sysUser.setCreateTime(new java.util.Date());
        
        try {
            // 调用远程用户注册接口
            R<Boolean> result = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
            
            if (result != null && result.getCode() == 200 && Boolean.TRUE.equals(result.getData())) {
                logger.info("商家用户注册成功，手机号: {}, 用户名: {}", mobile, sysUser.getUserName());
                
                // 注册成功后，需要获取用户ID
                // 由于注册接口只返回Boolean，我们需要通过用户名查询用户ID
                R<com.ruoyi.system.api.model.LoginUser> userInfoResult = remoteUserService.getUserInfo(mobile, SecurityConstants.INNER);
                if (userInfoResult != null && userInfoResult.getCode() == 200 && userInfoResult.getData() != null) {
                    Long userId = userInfoResult.getData().getSysUser().getUserId();
                    logger.info("获取到用户ID: {}", userId);
                    return userId;
                } else {
                    logger.error("获取用户信息失败，手机号: {}", mobile);
                    throw new ServiceException("获取用户信息失败");
                }
            } else {
                logger.error("商家用户注册失败，手机号: {}, 错误信息: {}", mobile, result != null ? result.getMsg() : "响应为空");
                throw new ServiceException("用户注册失败: " + (result != null ? result.getMsg() : "响应为空"));
            }
            
        } catch (Exception e) {
            logger.error("调用远程用户注册服务异常，手机号: {}", mobile, e);
            throw new ServiceException("调用用户注册服务异常: " + e.getMessage());
        }
    }

    /**
     * 为用户分配角色
     *
     * @param userId 用户ID
     * @param roleId 角色ID
     */
    private void assignUserRole(Long userId, Long roleId) {
        logger.info("开始为用户分配角色，用户ID: {}, 角色ID: {}", userId, roleId);
        
        try {
            // 构建请求参数
            Map<String, Object> roleBody = new HashMap<>();
            roleBody.put("userId", userId);
            roleBody.put("roleIds", new Long[]{roleId});
            
            // 调用远程角色分配接口
            R<Void> result = remoteUserService.assignUserRole(roleBody, SecurityConstants.INNER);
            
            if (result != null && result.getCode() == 200) {
                logger.info("用户角色分配成功，用户ID: {}, 角色ID: {}", userId, roleId);
            } else {
                logger.error("用户角色分配失败，用户ID: {}, 角色ID: {}, 错误信息: {}", 
                           userId, roleId, result != null ? result.getMsg() : "响应为空");
                throw new ServiceException("用户角色分配失败: " + (result != null ? result.getMsg() : "响应为空"));
            }
            
        } catch (Exception e) {
            logger.error("调用远程角色分配服务异常，用户ID: {}, 角色ID: {}", userId, roleId, e);
            throw new ServiceException("调用角色分配服务异常: " + e.getMessage());
        }
    }
}
